<?php
//------------------------
// 前台注册控制器
//-------------------------

namespace app\home\controller;

use think\Controller;
use app\common\model\User as UserModel;
use app\common\model\UserDetails as UserDetailsModel;
use \think\Request;


class Register extends Controller
{
    protected $UserModel;
	protected $UserDetailsModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->UserModel        = new UserModel();
        $this->UserDetailsModel = new UserDetailsModel();
    }


	// 注册页面
    public function index(){

        return $this->fetch();
    }

    // 注册处理
    public function registerProc(){
    	$data            = $this->request->param();

        $validate_result = $this->validate($data, 'Register');

        if ($validate_result !== true) {
                $this->error($validate_result);
        }

        $now = time();
        $emailCode = md5(uniqid());//uniqid函数基于以微秒计的当前时间，生成一个唯一的 ID。

        $request = Request::instance();
        	//获取当前系统域名
        	$url = $request -> domain() . DS . 'home/register/checkEmail/email_code/' . $emailCode;
        	$title = 'SF商城注册验证邮件';
        	$message =<<<HTML
        	欢迎成为SF商城会员，请点击以下链接完成email验证。（如非本人操作，请不要理会）
        	<p><a href="$url">点击完成验证</a></p>
HTML;

		//发送邮件
		$res = send_mail($data['email'],$title,$message);

		if ($res['status'] == 0) {
			$this->error('验证邮件发送失败，具体信息：' . $res['info']);
		}

		// 邮件发送成功后再把信息存进数据库
        $addData = array(
            'username'        => $data['username'],
            'email'           => $data['email'],
            'password'        => user_encryption($data['password']),
            'create_time'     => $now,
            'update_time'     => $now,
            'email_code'      => $emailCode
        );

        $res = $this->UserModel->save($addData);

        $user_id = $this->UserModel->id;

        // 在会员详表情插入一条关联会员id的数据
        $this->UserDetailsModel->save(array('user_id'=>$user_id));

        if ($res === false) {
            $this->error($this->UserModel->getError());
        } else {
            $this->success('注册成功，请登陆你的注册邮箱，验证邮件！');
        }

    }

    // 验证注册邮件
    public function checkEmail(){
    	$data            = $this->request->param();
    	if($data['email_code']){
			// 把这个验证码到数据库中比较一下即可
			$email = $this->UserModel->where('email_code', $data['email_code'])->find();
			if($email){
				// 设置这个账号为已验证
				$this->UserModel->where('id', $email['id'])->setField('email_code', '');
				$this->success('恭喜，验证通过', url('Login/index'));
			} else {
				$this->error('该邮件以失效');
			}
		} else {
			$this->error('非法操作');
		}

    }





}
